package org.viva.action;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class OssAction {

    @RequestMapping("/oss/down")
    public ResponseEntity<byte[]> get(HttpServletRequest request) throws IOException {
        String root = request.getSession().getServletContext().getRealPath("/") + "/oss";
        String path = request.getParameter("path");
        File file = new File(root + path);
        HttpHeaders headers = new HttpHeaders();
        String ct = printContentType(file.getAbsolutePath());
        if (ct != null) {
            headers.setContentType(MediaType.parseMediaType(ct));
        } else {
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        }
        headers.setContentDispositionFormData("attachment", file.getName());
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    private static String printContentType(String pathToFile) {
        Path path = Paths.get(pathToFile);
        String contentType = null;
        try {
            contentType = Files.probeContentType(path);
            return contentType;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
